<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/11/29 0029
 * Time: 上午 9:33
 */
namespace app\api\controller;


use app\admin\model\Department;
use app\admin\model\SupervisionDiscuss;
use app\admin\model\SupervisionEstimate;
use app\admin\model\SupervisionSchedule;
use app\admin\model\SupervisionUsers;
use app\common\BaseHelper;
use app\common\DictConstant;
use app\common\redis\Redis;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 督办
 * Class Supervision
 * @package app\api\controller
 */
class Supervision extends BaseController
{

    /**
     * 督办搜索
     */
    public function spervisionList(Request $request){
        if($request->isPost()){
            $param = $request->param();
            $start = 0;
            $length = 20;

            if(empty($param['userId'])){
                return show(config('status.ERROR_STATUS'),'用户异常','用户异常');
            }
            if(empty($param['keyword'])){
                return show(config('status.ERROR_STATUS'),'关键字不能为空','关键字不能为空');
            }
            if(empty($param['start'])){
                $start = $param['start'];
            }
            if(empty($param['length'])){
                $length = $param['length'];
            }

            $where = [
                'title' => ['like', '%' . $param['keyword'] . '%']
            ];

            // 我收到的督办
            $SupervisionUsers = SupervisionUsers::where('user_id', $param['userId'])->field('supervisionId')->select();
            $ids = array_column($SupervisionUsers, 'supervisionId');
            //$ids = implode(',', $ids);
            $idStr = '';
            foreach ($ids as $id) {
                $idStr .= ",'{$id}'";
            }
            $idStr = substr($idStr, 1);
            $whereStr = "(createUser = '{$param['userId']}') OR (id in ({$idStr}))";
            $Supervision = \app\admin\model\Supervision::where($where)->where($whereStr)->order('createDate DESC')->limit($start, $length)->select();
            $total = \app\admin\model\Supervision::where($where)->where($whereStr)->count();
            if($Supervision){
                return showTotal(config('status.SUCCESS_STATUS'), 'ok', $Supervision, $total);
            }else{
                return show(config('status.ERROR_STATUS'),'暂无数据',null);
            }
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //我创建的督办
    public function spervisionListFromMe(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['userId'])){
                return show(config('status.ERROR_STATUS'),'用户异常','用户异常');
            }
            $Supervision = \app\admin\model\Supervision::where('createUser',$param['userId'])->order('createDate DESC')->select();
            if($Supervision){
                return show(config('status.SUCCESS_STATUS'),'ok',$Supervision);
            }else{
                return show(config('status.ERROR_STATUS'),'暂无数据',null);
            }
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //我收到的督办
    public function spervisionListToMe(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['userId'])){
                return show(config('status.ERROR_STATUS'),'用户异常','用户异常');
            }
            $SupervisionUsers = SupervisionUsers::where('user_id',$param['userId'])->select();
            if($SupervisionUsers){
                $list = [];
                foreach ($SupervisionUsers as $v){
                    array_push($list,$v['supervisionId']);
                }
                if($list){
                    $Supervision = \app\admin\model\Supervision::all(function ($query) use ($list){
                        $query->where('id','in',$list)->order('complete_time ASC');
                    });
                    return show(config('status.SUCCESS_STATUS'),'ok',$Supervision);
                }else{
                    $Supervision = null;
                    return show(config('status.ERROR_STATUS'),'暂无数据',null);
                }

            }else{
                return show(config('status.ERROR_STATUS'),'暂无数据',null);
            }
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //督办详情
    public function letterEvaluateDetail(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['userId'])){
                return show(config('status.ERROR_STATUS'),'缺少参数','缺少参数');
            }
            $Supervision = \app\admin\model\Supervision::get($param['id']);
            $p_name = \app\admin\model\User::where('id',$Supervision->createUser)->value('p_name');
            $Supervision['p_name'] = $p_name;
            $SupervisionUsers = SupervisionSchedule::where('supervisionId',$Supervision->id)->order('huibao_time DESC')->select();
            foreach ($SupervisionUsers as &$v){
                $User = \app\admin\model\User::get($v['user_id']);
                $deptName = Department::where('id',$User['departmentId'])->value('name');
                $v['nickname'] = $User['p_name'];
                $v['deptName'] = $deptName;
            }
            $Supervision['supervisionScheduleVOS'] = $SupervisionUsers;
            $files = \app\admin\model\Image::where('relatedId',$Supervision->id)->select();
            if($Supervision->typeId == 2){
                //查询信访件附件
                $files = \app\admin\model\Image::where('relatedId',$Supervision->letterId)->select();
            }
            if($files){
                $list = [];
                for ($i=0;$i<count($files);$i++){
                    $arr = parse_url($files[$i]['imgUrl']);
                    $info = pathinfo($arr['path']);
                    $file_type =  $info['extension'];
                    $file_name= $info['filename'];
                    array_push($list,['link_url'=>$files[$i]['imgUrl'],'file_type'=>$file_type,'file_name'=>$file_name]);
                }
                $Supervision['imageAction'] = $list;

            }else{
                $Supervision['imageAction'] = null;
            }
            return show(config('status.SUCCESS_STATUS'),'ok',$Supervision);
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //创建督办
    public function create(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['staffId'])){
                return show(config('status.ERROR_STATUS'),'创建人异常','创建人异常');
            }
            if(empty($param['type'])){
                return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
            }else{
                if($param['type'] != 1 && $param['type'] != 2){
                    return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
                }
                if($param['type'] == 2){
                    if(empty($param['visitId'])){
                        return show(config('status.ERROR_STATUS'),'信访工作必须选择信访件','信访工作必须选择信访件');
                    }
                }
            }
            if(empty($param['supervisionUserList'])){
                return show(config('status.ERROR_STATUS'),'督办人不能为空','督办人不能为空');
            }
            Db::startTrans();
            try{
                $Supervision = new \app\admin\model\Supervision();
                $id = BaseHelper::getUUID();
                $Supervision->id = $id;
                $Supervision->typeId = $param['type'];
                $Supervision->title = $param['title'];
                $Supervision->letterId = isset($param['visitId'])?$param['visitId']:0;
                $Supervision->urgency_degree = $param['urgencyDegree'];
                $Supervision->content = $param['content'];
                $Supervision->complete_time = $param['completeTime'];
                $Supervision->createUser = $param['staffId'];
                $Supervision->save();
                $this->insertsupervisionusers($param['supervisionUserList'],$id);
                if(isset($param['fileIds']) && !empty($param['fileIds'])){
                    $this->insertFiles($param['fileIds'],$id);
                }
                if($param['type'] == 2){
                    //信访督办，需要改变信访件的状态
                    \app\admin\model\Letter::updateSattus($param['visitId']);
                }
                //向督办人发短信(加入到队列)
                $data = [];
                $data['title'] = $param['title'];
                $data['complete_time'] = $param['completeTime'];
                if($param['urgencyDegree'] == 1){
                    $data['urgency_degree'] = '一般';
                }elseif ($param['urgencyDegree'] == 2){
                    $data['urgency_degree'] = '紧急';
                }else{
                    $data['urgency_degree'] = '加急';
                }
                $Supervision = new \app\admin\service\Supervision();
                $Supervision->senMsg($data,$param['supervisionUserList']);
                Db::commit();
                return show(config('status.SUCCESS_STATUS'),'添加成功',$id);

            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.ERROR_STATUS'),$ex->getMessage(),$ex->getMessage());
            }
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    private function insertsupervisionusers($param,$supervisionId){
        $SupervisionUsers = new SupervisionUsers();
        $list = [];
        foreach (array_unique($param) as $v){
            $id = BaseHelper::getUUID();
            $user = \app\admin\model\User::where('id',$v)->field('departmentId')->find();
            array_push($list,['id'=>$id,'supervisionId'=>$supervisionId,'user_id'=>$v,'dept_id'=>$user->departmentId]);
        }
        $SupervisionUsers->saveAll($list,false);
    }
    private function insertFiles($imgIds,$relatedId){
        $Image = new \app\admin\model\Image();
        $list = [];
        foreach ($imgIds as $v){
            $id = BaseHelper::getUUID();
            array_push($list,['id'=>$id,'imgUrl'=>$v,'relatedId'=>$relatedId]);
        }
        $Image->saveAll($list,false);

    }

    //获取要编辑的督办信息

    public function getInfo(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
            }
            $Supervision = \app\admin\model\Supervision::get($param['id']);
            $Supervision['date'] = date('Y-m-d',strtotime($Supervision->complete_time));
            $Supervision['visit'] = '';
            if($Supervision->typeId == 2){
                $Letter = \app\admin\model\Letter::where('id',$Supervision->letterId)->field('id,title')->find();
                $Supervision['visit'] = $Letter;
            }
            $SupervisionUsers = SupervisionUsers::where('supervisionId',$Supervision->id)->select();
            $list = [];
            foreach ($SupervisionUsers as $v){
                $User = \app\admin\model\User::get($v['user_id']);
                if($User){
                    array_push($list,$User);
                }

            }
            $Supervision['supervisionUserList'] = $list;
            //附件
            $files = \app\admin\model\Image::where('relatedId',$Supervision->id)->select();

            if($files){
                $filesarr = [];
                foreach ($files as $v){
                    array_push($filesarr,$v['imgUrl']);
                }
                $Supervision['files'] = $filesarr;
            }else{
                $Supervision['files'] = [];
            }

            return show(config('status.SUCCESS_STATUS'),'ok',$Supervision);
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //修改督办
    public function update(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return show(config('status.ERROR_STATUS'),'缺少参数','缺少参数');
            }
            if(empty($param['type'])){
                return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
            }else{
                if($param['type'] != 1 && $param['type'] != 2){
                    return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
                }
                if($param['type'] == 2){
                    if(empty($param['visitId'])){
                        return show(config('status.ERROR_STATUS'),'信访工作必须选择信访件','信访工作必须选择信访件');
                    }
                }
            }
            if(empty($param['supervisionUserList'])){
                return show(config('status.ERROR_STATUS'),'督办人不能为空','督办人不能为空');
            }
            Db::startTrans();
            try{
                $Supervision = \app\admin\model\Supervision::get($param['id']);
                if($Supervision->schedule == 3){
                    return show(config('status.ERROR_STATUS'),'该督办已经结束','该督办已经结束');
                }
                if($param['staffId'] != $Supervision->createUser){
                    return show(config('status.ERROR_STATUS'),'创建人异常','创建人异常');
                }
                $Supervision->typeId = $param['type'];
                $Supervision->title = $param['title'];
                $Supervision->letterId = isset($param['visitId'])?$param['visitId']:0;
                $Supervision->urgency_degree = $param['urgencyDegree'];
                $Supervision->content = $param['content'];
                $Supervision->complete_time = $param['completeTime'];
                $Supervision->save();
                $data = [];
                $data['id'] = $param['id'];
                $data['title'] = $param['title'];
                $data['complete_time'] = $param['completeTime'];
                if($param['urgencyDegree'] == 1){
                    $data['urgency_degree'] = '一般';
                }elseif ($param['urgencyDegree'] == 2){
                    $data['urgency_degree'] = '紧急';
                }else{
                    $data['urgency_degree'] = '加急';
                }
                $this->updatesupervisionusers($param['supervisionUserList'],$data);
                if(isset($param['fileIds'])){
                    $this->updateFiles($param['fileIds'],$param['id']);
                }
                if($param['type'] == 2){
                    //信访督办，需要改变信访件的状态
                    \app\admin\model\Letter::updateSattus($param['visitId']);
                }
                Db::commit();
                return show(config('status.SUCCESS_STATUS'),'修改成功','修改成功');

            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.ERROR_STATUS'),$ex->getMessage(),$ex->getMessage());
            }
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    private function updatesupervisionusers($param,$data){
        $SupervisionUsersList = SupervisionUsers::where('supervisionId',$data['id'])->field('user_id')->select();
        $alreadylist = [];
        $dellist = [];
        foreach ($SupervisionUsersList as $v){
            $flag = true;
            for ($i=0;$i<count($param);$i++){
                if($param[$i] == $v['user_id']){
                    $flag = false;
                    break;
                }
            }
            if($flag){
                array_push($dellist,$v['user_id']);
            }
        }

        for($i=0;$i<count($param);$i++){
            $flag = true;
            foreach ($SupervisionUsersList as $v){
                if($param[$i] == $v['user_id']){
                    $flag = false;
                    break;
                }
            }
            if($flag){
                array_push($alreadylist,$param[$i]);
            }
        }
        if($dellist){
            SupervisionUsers::where('supervisionId',$data['id'])->where('user_id','in',$dellist)->delete();
        }
        if($alreadylist){
            $list = [];
            $alreadylist = array_unique($alreadylist);
            foreach ($alreadylist as $v){
                $id = BaseHelper::getUUID();
                $user = \app\admin\model\User::where('id',$v)->field('departmentId')->find();
                array_push($list,['id'=>$id,'supervisionId'=>$data['id'],'user_id'=>$v,'dept_id'=>$user->departmentId]);
            }
            $SupervisionUsers = new SupervisionUsers();
            $SupervisionUsers->saveAll($list,false);
            //发短信(加入到队列)
            $supserver = new \app\admin\service\Supervision();
            unset($data['id']);
            $supserver->senMsg($data,$alreadylist);
        }

    }

    private function updateFiles($imgIds,$relatedId){

        \app\admin\model\Image::where('relatedId',$relatedId)->delete();
        if(!empty($imgIds)){
            $Image = new \app\admin\model\Image();
            $list = [];
            foreach ($imgIds as $v){
                $id = BaseHelper::getUUID();
                array_push($list,['id'=>$id,'imgUrl'=>$v,'relatedId'=>$relatedId]);
            }
            $Image->saveAll($list,false);
        }
    }

    //获取可选择的信访件列表
    public function getLetterList(){
        $where = [
            'status' => 1
        ];
        $Letter = \app\admin\model\Letter::where($where)->select();
        if($Letter){
            return show(config('status.SUCCESS_STATUS'),'ok',$Letter);
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',NULL);
        }
    }

    //获取督办可指派的工作人员
    public function getSuperviseUserList(Request $request){
        $param = $request->param();
        if($param['type'] == 1 || $param['type'] == 2){
            $Department = Department::where('status',1)->field('id,name')->select();
            foreach ($Department as &$v){
                $User = \app\admin\model\User::where(['departmentId'=>$v['id'],'status'=>1])->where('type','in',[0,1])->field('id,p_name,type,p_imgUrl,menuId')->select();
                $res = [];
                if($param['type'] == 1){
                    foreach ($User as $value){
                        $access = explode(',',$value['menuId']);
                        if(in_array(DictConstant::SUPERVISION,$access)){
                            array_push($res,$value);
                        }
                    }
                    $v['sysUserVOList'] = $res;
                }else{
                    $v['sysUserVOList'] = $User;
                }
            }
            return show(config('status.SUCCESS_STATUS'),'ok',$Department);
        }else{
            return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
        }
    }

    //编辑时删除指派人员
    public function deluser_url(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['supid'])){
                return show(config('status.ERROR_STATUS'),'缺少参数','缺少参数');
            }
            $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$param['supid'],'user_id'=>$param['id']])->find();
            if($SupervisionUsers->speed == 1){
                return show(config('status.SUCCESS_STATUS'),'ok','ok');
            }else{
                return show(config('status.ERROR_STATUS'),'此指派人已经开始督办，不能删除',NULL);

            }

        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //删除督办
    public function del(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id'])){
                return show(config('status.ERROR_STATUS'),'缺少参数','缺少参数');
            }
            Db::startTrans();
            try{
                $Supervision = \app\admin\model\Supervision::get($param['id']);
                if($Supervision->schedule != 1){
                    return show(config('status.ERROR_STATUS'),'已经开始办理，不能删除','已经开始办理，不能删除');
                }else{
                    $Supervision->delete();
                    //删除督办人
                    SupervisionUsers::where('supervisionId',$Supervision->id)->delete();
                    //删除附件
                    $filescount = \app\admin\model\Image::where('relatedId',$Supervision->id)->count();
                    if($filescount>0){
                        \app\admin\model\Image::where('relatedId',$Supervision->id)->delete();
                    }
                    //如果有交流删除交流
                    $SupervisionDiscuss = SupervisionDiscuss::where('supervisionId',$param['id'])->find();
                    if($SupervisionDiscuss){
                        SupervisionDiscuss::destroy(function ($query) use ($param){
                            $query->where('supervisionId','=',$param['id']);
                        });
                    }
                    //如果是信访督办，则要恢复信访件的正常状态
                    if($Supervision->typeId == 2){
                        $Letter = \app\admin\model\Letter::get($Supervision->letterId);
                        $Letter->status = 1;
                        $Letter->save();
                    }
                    Db::commit();
                    return show(config('status.SUCCESS_STATUS'),'ok','ok');
                }
            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.ERROR_STATUS'),$ex->getMessage(),'删除失败');
            }

        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //新增/编辑督办办理
    public function addSupervisionSchedule(Request $request){
        if($request->isPost()){
            $param = $request->param();
            $supervisionId = $param['supervisionId'];
            $userId = $param['userId'];
            if(empty($supervisionId) || empty($userId)){
                return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
            }
            if($param['schedule']!=2 && $param['schedule']!=3){
                return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
            }
            Db::startTrans();
            try{
                $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$supervisionId,'user_id'=>$userId])->lock(true)->find();
                if(!$SupervisionUsers){
                    return show(config('status.ERROR_STATUS'),'该用户信息异常','该用户信息异常');
                }
                if(empty($param['id'])){
                    //新增
                    if($SupervisionUsers->speed == 3){
                        return show(config('status.ERROR_STATUS'),'您已经完成该督办，不能新增','您已经完成该督办，不能新增');
                    }
                    $model = new SupervisionSchedule();
                    $id = BaseHelper::getUUID();
                    $model->id = $id;
                }else{
                    //修改
                    $model = SupervisionSchedule::get($param['id']);
                }
                $Supervision = \app\admin\model\Supervision::get($param['supervisionId']);
                if($Supervision->schedule == 3){
                    return show(config('status.ERROR_STATUS'),'该督办已经结束','该督办已经结束');
                }
                $model->supervisionId = $supervisionId;
                $model->user_id = $userId;
                $model->content = $param['content'];
                $model->s_speed = $param['schedule'];
                $model->huibao_time = date('Y-m-d H:i',time());
                $model->save();
                $SupervisionUsers->speed = $param['schedule'];
                $SupervisionUsers->save();
                $allcount = SupervisionUsers::where(['supervisionId'=>$supervisionId])->count();
                $count = SupervisionUsers::where(['supervisionId'=>$supervisionId,'speed'=>3])->count();
                if($count<$allcount){
                    $Supervision->schedule = 2;
                }else{
                    $Supervision->schedule = 3;
                    $Supervision->actual_time = date('Y-m-d H:i:s',time());
                }
                $Supervision->save();
                if($Supervision->typeId == 2){
                    $Letter = \app\admin\model\Letter::get($Supervision->letterId);
                    if($Supervision->schedule == 3){
                        $Letter->status = 4;
                        $Letter->save();
                    }
                }
                Db::commit();
                return show(config('status.SUCCESS_STATUS'),'新增成功','新增成功');
            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.ERROR_STATUS'),'增加失败','增加失败');
            }
        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //删除督办办理
    public function delSchedule(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['id']) || empty($param['userId']) || empty($param['sspeed'])){
                return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
            }
            if($param['sspeed'] != 2 && $param['sspeed'] != 3){
                return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
            }
            Db::startTrans();
            try{
                $SupervisionSchedule = SupervisionSchedule::get($param['id']);
                if($SupervisionSchedule->user_id == $param['userId']){
                    $Supervision = \app\admin\model\Supervision::get($SupervisionSchedule->supervisionId);
                    if($Supervision->schedule == 3){
                        return show(config('status.ERROR_STATUS'),'该督办已经结束','该督办已经结束');
                    }
                    $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$Supervision->id,'user_id'=>$SupervisionSchedule->user_id])->find();
                    if($SupervisionSchedule->s_speed == 3 && $param['sspeed'] == 3){
                        $SupervisionUsers->speed = 2;
                        $SupervisionUsers->save();
                    }
                    $SupervisionSchedule->delete();
                    Db::commit();
                    return show(config('status.SUCCESS_STATUS'),'删除成功','删除成功');
                }else{
                    return show(config('status.ERROR_STATUS'),'用户异常','用户异常');
                }

            }catch (Exception $ex){
                Db::rollback();
                return show(config('status.ERROR_STATUS'),'删除失败','删除失败');
            }

        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //督办交流
    public function showDiscuss(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $discussList = SupervisionDiscuss::where('supervisionId',$param['id'])->order('createDate DESC')->select();
        if($discussList){
            foreach ($discussList as &$value){
                if(!empty($value['to_user_id'])){
                    $toNickname = \app\admin\model\User::where('id',$value['to_user_id'])->value('p_name');
                    $value['toNickname'] = $toNickname;
                }else{
                    $value['toNickname'] = '';
                }
                $user = \app\admin\model\User::where('id',$value['user_id'])->field('p_name,p_imgUrl')->find();

                $value['nickname'] = $user->p_name;
                $value['headimg'] = $user->p_imgUrl;
            }
        }

        $joinedList = SupervisionUsers::where('supervisionId',$param['id'])->select();
        $res = [];
        foreach ($joinedList as $v){
            $User = \app\admin\model\User::where('id',$v['user_id'])->field('id,p_name,p_imgUrl')->find();
            array_push($res,$User);
        }
        $data['supervisionDiscussEOS'] = $discussList;
        $data['supervisionUserList'] = $res;
        return show(config('status.SUCCESS_STATUS'),'ok',$data);
    }

    //发布督办交流
    public function addDiscuss(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['permissionId']) || empty($param['userId'])){
                return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
            }

            $SupervisionUsers = SupervisionUsers::where(['supervisionId'=>$param['permissionId'],'user_id'=>$param['userId']])->find();
            $Supervision = \app\admin\model\Supervision::get($param['permissionId']);
            if(!$SupervisionUsers && $param['userId'] != $Supervision->createUser){
                return show(config('status.ERROR_STATUS'),'您不是创建人，也不是督办人，不能交流','您不是创建人，也不是督办人，不能交流');
            }
            $model = new SupervisionDiscuss();
            $id = BaseHelper::getUUID();
            $model->id = $id;
            if(empty($param['toUserId'])){
                $model->is_all = 1;
                $model->to_user_id = 0;
            }else{
                if($param['toUserId'] == $param['userId']){
                    return show(config('status.ERROR_STATUS'),'不能回复自己','不能回复自己');
                }else{
                    $model->is_all = 0;
                    $model->to_user_id = $param['toUserId'];
                }

            }
            $model->user_id = $param['userId'];
            $model->supervisionId = $param['permissionId'];
            $model->content = $param['content'];
            if($model->save()){
                return show(config('status.SUCCESS_STATUS'),'发布成功','发布成功');
            }else{
                return show(config('status.ERROR_STATUS'),'发布失败','发布失败');
            }

        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //删除督办交流
    public function delDiscuss(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if(empty($param['userId']) || empty($param['id'])){
                return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
            }
            $SupervisionDiscuss = SupervisionDiscuss::get($param['id']);
            if($SupervisionDiscuss){
                if($SupervisionDiscuss->user_id == $param['userId']){
                    $res = SupervisionDiscuss::where('id',$param['id'])->delete();
                    if($res){
                        return show(config('status.SUCCESS_STATUS'),'删除成功','删除成功');
                    }else{
                        return show(config('status.ERROR_STATUS'),'删除失败','删除失败');
                    }
                }else{
                    return show(config('status.ERROR_STATUS'),'用户信息异常','用户信息异常');
                }

            }else{
                return show(config('status.ERROR_STATUS'),'该交流不存在','该交流不存在');
            }

        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //督办评价
    public function letterEvaluate(Request $request){
        if($request->isPost()){
            $param = $request->param();
            if($param['tag'] !=0 && $param['tag'] != 1){
                return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
            }
            if($param['tag'] == 0){
                if(empty($param['supervisionId']) || empty($param['userId'])){
                    return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
                }
                //创建督办的人评价
                $Supervision = \app\admin\model\Supervision::get($param['supervisionId']);
                if($Supervision){
                    if($Supervision->createUser != $param['userId']){
                        return show(config('status.ERROR_STATUS'),'用户不合法','用户不合法');
                    }
                    if($Supervision->schedule != 3){
                        return show(config('status.ERROR_STATUS'),'该督办不能评价','该督办不能评价');
                    }else{
                        if(isset($param['id']) && !empty($param['id'])){
                            //修改
                            $model = SupervisionEstimate::get($param['id']);
                            if($model->estimate == 1){
                                return show(config('status.ERROR_STATUS'),'该评价不能修改','该评价不能修改');
                            }
                        }else{
                            $SupervisionEstimate = SupervisionEstimate::where('supervisionId',$param['supervisionId'])->find();
                            if($SupervisionEstimate){
                                return show(config('status.ERROR_STATUS'),'已经评价过，不能新增','已经评价过，不能新增');
                            }else{
                                //新增
                                $model = new SupervisionEstimate();
                                $id = BaseHelper::getUUID();
                                $model->id = $id;
                                $model->supervisionId = $param['supervisionId'];
                            }

                        }
                        $model->estimate = $param['estimate'];
                        $model->user_id = $param['userId'];
                        $model->e_content = $param['content'];
                        $model->save();
                        return show(config('status.SUCCESS_STATUS'),'评价完成','评价完成');
                    }
                }else{
                    return show(config('status.ERROR_STATUS'),'该督办不存在','该督办不存在');
                }
            }else{
                if(empty($param['letterId']) || empty($param['userId'])){
                    return show(config('status.ERROR_STATUS'),'参数不合法','参数不合法');
                }
                //信访人评价
                $Letter = \app\admin\model\Letter::get($param['letterId']);
                if($Letter->user_id != $param['userId']){
                    return show(config('status.ERROR_STATUS'),'请登录信访用户','请登录信访用户');
                }
                if($Letter->reply){
                    return show(config('status.ERROR_STATUS'),'您已经评价过了','您已经评价过了');
                }
                $Letter->u_content = $param['content'];
                $Letter->reply = $param['estimate'];
                $Letter->save();
                return show(config('status.SUCCESS_STATUS'),'评价完成','评价完成');
            }


        }else{
            return show(config('status.ERROR_STATUS'),'非法请求','非法请求');
        }
    }

    //获取评价
    public function showEvaluate(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $isshowpingjia = false;
        $isshowedit = false;
        $SupervisionEstimate = SupervisionEstimate::where('supervisionId',$param['id'])->find();
        if($SupervisionEstimate){
            $p_name = \app\admin\model\User::where('id',$SupervisionEstimate->user_id)->value('p_name');
            $SupervisionEstimate['p_name'] = $p_name;
            if($SupervisionEstimate->estimate != 1){
                $isshowedit = true;
            }

        }else{
            $isshowpingjia = true;
        }
        $data['pingjiainfo'] = $SupervisionEstimate;
        $data['showpingjia'] = $isshowpingjia;
        $data['isshowedit'] = $isshowedit;
        $data['visitspingjia'] = null;
        $Supervision = \app\admin\model\Supervision::get($param['id']);
        if($Supervision->typeId == 2 && !empty($Supervision->letterId)){
            $Letter = \app\admin\model\Letter::where('id',$Supervision->letterId)->field('reply,u_content')->find();
            if($Letter->reply){
                $data['visitspingjia'] = $Letter;
            }
        }
        return show(config('status.SUCCESS_STATUS'),'ok',$data);
    }
    //根据id获取评价
    public function getEvaluate(Request $request){
        $param = $request->param();
        if(empty($param['id'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $data = SupervisionEstimate::get($param['id']);
        if($data){
            return show(config('status.SUCCESS_STATUS'),'ok',$data);
        }else{
            return show(config('status.ERROR_STATUS'),'暂无数据',null);
        }
    }

    //督办统计
    public function statistics(Request $request){
        $param = $request->param();
        if($param['cur']!=0 && $param['cur']!=1 && $param['cur']!=2){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        if(empty($param['userId'])){
            return show(config('status.ERROR_STATUS'),'参数错误','参数错误');
        }
        $redis = Redis::getRedisConn();
        if($param['cur'] == 0){
            $redisKey = 'all_Statistics';
        }else{
            $redisKey = $param['userId'] . '_' . $param['cur'];
        }
        $value = $redis->get($redisKey);
        if($value){
            $value_serl = @unserialize($value);
            if(is_object($value_serl)||is_array($value_serl)){
                return $value_serl;
            }
            return $value;
        }else{
            $ser = new \app\api\service\Supervision($param['userId'],$param['cur']);
            $result = $ser->Statistics();
            if(is_object($result)||is_array($result)){
                $value = serialize($result);
            }
            $redis->set($redisKey,$value,180);  //缓存3分钟
            return $result;
        }
    }

}